#------------------------------------------------------------------------------
# Import libraries
#------------------------------------------------------------------------------

rm(list=ls())
library(LalRUtils)
libreq(tidyverse, data.table, zoo, tictoc, fst, fixest, PanelMatch, patchwork,
       rio, magrittr, janitor, did, panelView, ggiplot, tictoc, binsreg, interflex)
set.seed(42)
theme_set(lal_plot_theme())

#------------------------------------------------------------------------------





#------------------------------------------------------------------------------
# Define Paths
#------------------------------------------------------------------------------

# R studio
setwd( dirname(rstudioapi::getActiveDocumentContext()$path) )
# R default : unccoment if you use default R
# setwd(getSrcDirectory(function(){})[1])

#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# Load Data
#------------------------------------------------------------------------------

vcf <- fread("vcf_data_complete.csv", sep = ",")
setnames( vcf, "d", "D")
vcf_data <- copy( vcf )
gfc <- fread("gfc_dta.csv" )


#------------------------------------------------------------------------------




#------------------------------------------------------------------------------
# FigureA2
#------------------------------------------------------------------------------


# %%
vcf = vcf_data[year>= 1990]
fifth_sched_pre_2k = c("Andhra Pradesh", "Chhattisgarh", "Gujarat", "Himachal Pradesh",
                       "Orissa", "Rajasthan", "Madhya Pradesh")
pri = vcf[year<=1999 & state %in% fifth_sched_pre_2k]
pri[, first_panch_elec := fcase(
  state == "Andhra Pradesh", 1995,
  state == "Chhattisgarh", 1995,
  state == "Gujarat", 1995,
  state == "Madhya Pradesh", 1994,
  state == "Himachal Pradesh", 1995,
  state == "Orissa", 1997,
  state == "Rajasthan", 1995
)]

# %% flip treatment status since PRI treatment is PESA control and vice vers
pri[, time_pri := year - first_panch_elec]
pri[, D := (1 - sch) * (year >= first_panch_elec)]
pri[, nsch := (1 - sch)]

# %%
state_status = pri[, .(out = 1, treat = max(D)), .(state, year)]
f0 = panelview(out ~ treat,
               data = as.data.frame(state_status),
               index = c("state","year"),
               xlab = "Year", ylab = "State", 
               main = "Scheduled Areas PESA Status \n VCF Cell Level Data",
               by.timing = TRUE, legendOff = TRUE,
               background = "white", 
               cex.main = 38, cex.axis= 35, 
               cex.lab = 38, ) 

ggsave( "appendix_figureA2.pdf", 
        height = 10, width = 22, device = cairo_pdf)
